package com.scedu.controller;

import com.scedu.entity.Emp;
import com.scedu.entity.User;
import com.scedu.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/emp")
@Slf4j
public class EmpController {

    @Autowired
    private EmpService empService;

    @GetMapping("/findAll")
    public ModelAndView findALL(Map<String,Object> map,
                                HttpSession httpSession){
        List<Emp> empList=empService.findAll();
        log.info("查找所有用户");
        User user=new User();
        if (httpSession.getAttribute("user")!=null){
            BeanUtils.copyProperties(httpSession.getAttribute("user"),user); //读取session
            map.put("user", user);
        }


        map.put("empList", empList);
        return new ModelAndView("emp", map);
    }

    @PostMapping("/add")
    public String add(@Valid Emp emp, BindingResult bindingresult){
        if (bindingresult.hasErrors()) {
            //有验证错误
            log.info("验证错误！"+bindingresult.toString());
            return "redirect:/toadd"; //跳转到添加界面
        }
        empService.save(emp);
        return "redirect:/emp/findAll"; //跳转到列表界面
    }
    @GetMapping("/del")
    public String del(@RequestParam(value = "id",required = false) String id) {
        if (id!=null){
            empService.del(id);
        }
        return "redirect:/emp/findAll"; //跳转到列表界面
    }

    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam(value = "id",required = true) String id, Map<String,Object> map){
        log.info("修改用户，编号={}",id);
        if (id!=null){
            Emp emp=empService.find(id);
            map.put("emp", emp);
            return new ModelAndView("/editemp",map);
        }
        return new ModelAndView("/editemp",map);
      // return new ModelAndView("/editemp",map);
      // return "/editemp.html";
    }

    @PostMapping("/doedit")
    public String doedit(@Valid Emp emp, BindingResult bindingresult){
        if (bindingresult.hasErrors()) {
            //有验证错误
            System.out.println("验证错误！"+bindingresult.toString());
            return "redirect:/emp/findAll"; //跳转到列表界面
        }
        empService.edit(emp);
        return "redirect:/emp/findAll"; //跳转到列表界面
    }
}
